package com.edu.zut.hb.software.server.service;

import com.edu.zut.hb.software.server.pojo.Mqmsg;
import org.apache.activemq.command.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

@Component
public class MqConsumer {
    private static final Logger logger = LoggerFactory.getLogger(MqConsumer.class);

    @Autowired
    IMqmsgService mqmsgService;
    //    MqConsumer@JmsListener(destination = "${topic.name}")
//    public void receiveTopic01(String text) {
//        System.out.println("receiveTopic1接收到Topic消息 : " + text);
//    }
//
//    @JmsListener(destination = "${topic.name}")
//    public void receiveTopic02(String text) {
//        System.out.println("receiveTopic2接收到Topic消息 : " + text);
//    }
    @Value("${queue.name}")
    String ququeName;

    //    @JmsListener(destination = "${queue.name}")
//    public void receiveQueue(String text){
//        try {
//            mqmsgService.save(new Mqmsg("201900164765","郭学一",text));
//            logger.info("接收到"+ququeName+"的消息 :"+text);
//        }catch (Exception e){
//            logger.error("接收信息中含有非法字符");
//        }
//
//    }
    @JmsListener(destination = "${queue.name}")
    public void receiveQueue(Message message) {
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            try {
                logger.info("接收消息：" + textMessage.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (message instanceof ObjectMessage) {
            ObjectMessage objectMessage = (ObjectMessage) message;
            try {
                Mqmsg mqmsg = (Mqmsg) objectMessage.getObject();
                mqmsgService.save(mqmsg);
                logger.info("接收Object消息：" + mqmsg.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
